﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using System.Security.Cryptography;
using System.Text;
using VietThinks.Website.Models;
using Infrastructure;
namespace VietThinks.Website
{
    public static class UrlHelperExtensions
    {
        static UrlHelperExtensions()
        {
            PathToImages = GetAppSettingValueOrDefault("PathToImages", "~/");
            PathToProductImages = GetAppSettingValueOrDefault("PathToProductImages", "~/");
            PathToLayoutImages = GetAppSettingValueOrDefault("PathToLayoutImages", "~/");
            PathToPromoImages = GetAppSettingValueOrDefault("PathToPromoImages", "~/");
            PathToMedia = GetAppSettingValueOrDefault("PathToMedia", "~/");
            PathToStyles = GetAppSettingValueOrDefault("PathToStyles", "~/");
            PathToScripts = GetAppSettingValueOrDefault("PathToScripts", "~/");

            ResourceVersion = GetAppSettingValueOrDefault("StaticComponentVersion", "1");
        }

        public static string PathToImages { get; set; }
        public static string PathToProductImages { get; set; }
        public static string PathToLayoutImages { get; set; }
        public static string PathToPromoImages { get; set; }
        public static string PathToStyles { get; set; }
        public static string PathToScripts { get; set; }
        public static string PathToMedia { get; set; }

        private static string ResourceVersion { get; set; }

        private static string GetAppSettingValueOrDefault(string key, string @defaultValue)
        {
            if (ConfigurationManager.AppSettings.AllKeys.Contains(key))
            {
                return ConfigurationManager.AppSettings[key];
            }

            return @defaultValue;
        }

        public static string ProductResizedImage(this UrlHelper urlHelper, string path, string filename)
        {
            var resourceName = string.Format("{0}/{1}/{2}", path, ConfigurationManager.AppSettings["ResizedImageFolder"], filename);

            return ProductImage(urlHelper, resourceName);
        }

        public static string ProductResizedImage(this UrlHelper urlHelper, string path, string filename, ImageSize size)
        {
            string extension = System.IO.Path.GetExtension(filename);
            string _fileName = System.IO.Path.GetFileNameWithoutExtension(filename);
            int width = 0, height = 0;
            switch (size)
            {
                case ImageSize.Size75x75:
                    width = height = 75;
                    break;
                case ImageSize.Size100x100:
                    width = height = 100;
                    break;
                case ImageSize.Size120x120:
                    width = height = 120;
                    break;
                case ImageSize.Size128x128:
                    width = height = 128;
                    break;
                case ImageSize.Size140x140:
                    width = height = 140;
                    break;
                case ImageSize.Size144x144:
                    width = height = 144;
                    break;
                case ImageSize.Size204x204:
                    width = height = 204;
                    break;
                case ImageSize.Size215x215:
                    width = height = 215;
                    break;
                case ImageSize.Size220x220:
                    width = height = 220;
                    break;
                case ImageSize.Size264x264:
                    width = height = 264;
                    break;
            }
            var resourceName = string.Format("{0}/{1}/{2}-{3}-{4}{5}"
                , path
                , ConfigurationManager.AppSettings["ResizedImageFolder"]
                , _fileName
                , width
                , height
                , extension);

            return ProductImage(urlHelper, resourceName);
        }

        public static string ProductImage(this UrlHelper urlHelper, string resourceName)
        {
            return urlHelper.Content(string.Format("/resource/images/{0}/{1}", AdhocReplace(ResourceVersion), resourceName.ToLower()));
        }

        public static string OptionResizedImage(this UrlHelper urlHelper, string supplierName, string resourceName)
        {
            string pathToOptionImage;

            if (!resourceName.Contains(ConfigurationManager.AppSettings["OptionNoImageFileName"]))
            {
                pathToOptionImage = string.Format("{0}{1}/{2}/{3}/",
                                                      ConfigurationManager.AppSettings["PathToProductImages"],
                                                      ConfigurationManager.AppSettings["OptionImageFolder"],
                                                      supplierName,
                                                      ConfigurationManager.AppSettings["ResizedImageFolder"].ToLower());
            }
            else
            {
                pathToOptionImage = string.Format("{0}{1}/",
                                                      ConfigurationManager.AppSettings["PathToProductImages"],
                                                      ConfigurationManager.AppSettings["OptionImageFolder"]);
            }

            return urlHelper.Content(VirtualPathUtility.Combine(pathToOptionImage, resourceName));
        }

        public static string OptionImage(this UrlHelper urlHelper, string path, string resourceName)
        {
            return string.Format("/Content/images/{0}/{1}/{2}",
                ConfigurationManager.AppSettings["OptionImageFolder"],
                path,
                resourceName);
        }

        public static string LayoutImage(this UrlHelper urlHelper, string resourceName)
        {
            return urlHelper.Content(VirtualPathUtility.Combine(PathToImages, resourceName));
        }

        public static string PromoImage(this UrlHelper urlHelper, string resourceName)
        {
            if (!string.IsNullOrEmpty(resourceName))
            {
                return urlHelper.Content(VirtualPathUtility.Combine(PathToPromoImages, resourceName));
            }

            return string.Empty;
        }

        public static string Style(this UrlHelper urlHelper, string resourceName)
        {
#if !DEBUG
            return urlHelper.Content(string.Format("/resource/stylesheet/{0}/{1}", AdhocReplace(ResourceVersion), resourceName.ToLower()));
#else
            return urlHelper.Content(string.Format("/Content/stylesheets/{0}", resourceName.ToLower()));
#endif
        }

        public static string Script(this UrlHelper urlHelper, string resourceName)
        {
#if !DEBUG
            return urlHelper.Content(string.Format("/resource/script/{0}/{1}", AdhocReplace(ResourceVersion), resourceName.ToLower()));
#else
            return urlHelper.Content(string.Format("/Scripts/{0}", resourceName.ToLower()));
#endif
        }

        public static string Media(this UrlHelper urlHelper, string resourceName)
        {
            return urlHelper.Content(VirtualPathUtility.Combine(PathToMedia, resourceName));
        }

        public static string SubSegment(this UrlHelper urlHelper, string segment)
        {
            return urlHelper.RequestContext.HttpContext.Request.Path.TrimEnd('/') + "/" + segment;
        }

        public static string GlobalType(this UrlHelper urlHelper)
        {
            return GlobalType(urlHelper, BrowsingType.empty);
        }

        public static string GlobalType(this UrlHelper urlHelper, BrowsingType browsingType)
        {
            if (browsingType != BrowsingType.empty)
            {
                return string.Format("?b={0}", browsingType);
            }

            var httpRequest = urlHelper.RequestContext.HttpContext.Request;

            return string.IsNullOrEmpty(httpRequest.ToString())
                       ? string.Empty
                       : string.IsNullOrEmpty(httpRequest["b"])
                             ? string.Empty
                             : httpRequest.RawUrl.Contains("?b") ? string.Format("?b={0}", httpRequest["b"]) : string.Format("&b={0}", httpRequest["b"]);
        }

        public static string CurrentFilter(this UrlHelper urlHelper)
        {
            var httpRequest = urlHelper.RequestContext.HttpContext.Request;

            return string.IsNullOrEmpty(httpRequest["N"])
                       ? string.Empty
                       : string.Format("&N={0}", httpRequest["N"].Replace(" ", "+"));
        }

        public static string Page(this UrlHelper urlHelper, int page)
        {
            return String.Format("{0}?page={1}",
                urlHelper.RequestContext.HttpContext.Request.Path.TrimEnd('/'),
                page);
        }

        public static string Catalog(this UrlHelper urlHelper, CatalogPathType type, string path)
        {
            return urlHelper.Content(String.Format("~/{0}/{1}", type, path));
        }

        public static string Print(this UrlHelper urlHelper, string path)
        {
            return urlHelper.Content(String.Format("~/Print/{0}", path));
        }

        private static string Md5Hash(string input)
        {
            byte[] inputBytes = Encoding.UTF8.GetBytes(input);

            MD5 encryptType = new MD5CryptoServiceProvider();

            byte[] outputBytes = encryptType.ComputeHash(inputBytes);

            return BitConverter.ToString(outputBytes).Replace("-", "").ToLower();
        }

        private static string AdhocReplace(string input)
        {
            if (!string.IsNullOrEmpty(input))
            {
                if (input.Contains("/"))
                {
                    return input.Replace("/", ".");
                }

                return input;
            }

            return string.Empty;
        }

        #region catalog

        public static string Catalog(this UrlHelper helper, string path)
        {
            return string.Format("/catalog/{0}", path.TrimStart('/'));
        }

        #endregion

        #region cPath, mPath

        public static string path(this UrlHelper urlHelper, string path)
        {
            return string.Format("/catalog/default/{0}Path/{1}", cPath_Or_mPath(path), path);
        }

        #endregion

        #region family

        public static string family(this UrlHelper urlHelper, string path, string pfam_id)
        {
            if (path.IsEmpty())
                return string.Format("/catalog/product_family_info/pfam_id/{0}", pfam_id);
            return string.Format("/catalog/product_family_info/{0}Path/{1}/pfam_id/{2}", cPath_Or_mPath(path), path, pfam_id);
        }

        #endregion

        #region product

        public static string product(this UrlHelper urlHelper, string pfam_id, string products_id)
        {
            return string.Format("/catalog/product_info/pfam_id/{0}/products_id/{1}", pfam_id, products_id);
        }
        public static string productfromSubCat(this UrlHelper urlHelper, string pfam_id, string products_id)
        {
            return string.Format("/catalog/product_info?pfam_id={0}&products_id={1}", pfam_id, products_id);
        }

        #endregion

        #region Gttk

        public static string Gttk(this UrlHelper urlHelper)
        {
            return string.Format("/catalog/{0}", "goodthingstoknow.html");
        }

        public static string pathToGttk(this UrlHelper urlHelper, string path)
        {
            return string.Format("/catalog/gttk_article.php/cPath/{0}", path);
        }

        //public static string pathToGttk(this UrlHelper urlHelper, string path, bool isCat)
        //{
        //    if (isCat)
        //        return string.Format("/catalog/gttk.php/cPath/{0}", path);
        //    return string.Format("/catalog/gttk_article.php/cPath/{0}", path);
        //}

        public static string pathToGttk(this UrlHelper urlHelper, string path, string hashBackTop)
        {
            return string.Format("/catalog/gttk_article.php/cPath/{0}/hasBackTo/no", path);
        }

        #endregion

        private static string cPath_Or_mPath(string code)
        {
            if (string.IsNullOrEmpty(code)) return string.Empty;
            return code.StartsWith("MAN") ? "m" : "c";
        }
    }

    public enum CatalogPathType
    {
        category,
        brand,
        shop,
        browseby,
        pf,
        pd
    }

    public enum BrowsingType
    {
        empty,
        see,
        search,
        onsale,
        sitemap
    }
}